<template>
  <div class="receivable-summary">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <!-- 日期范围 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="filter.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-value="[new Date('2025-06-01'), new Date('2025-06-26')]"
        />
      </el-form-item>

      <!-- 汇总依据 -->
      <el-form-item label="汇总依据">
        <el-select v-model="filter.summaryBy" placeholder="请选择">
          <el-option label="客户" value="customer" />
          <el-option label="客户类别" value="customerCategory" />
          <el-option label="销售人员" value="salesman" />
        </el-select>
      </el-form-item>

      <!-- 客户选择（弹窗） -->
      <el-form-item label="客户">
        <el-button type="primary" @click="openDialog('customer')">
          {{ selectedCustomer.label || "请选择客户" }}
        </el-button>
      </el-form-item>

      <!-- 客户类别选择（树弹窗） -->
      <el-form-item label="客户类别">
        <el-button type="primary" @click="openDialog('customerCategory')">
          {{ selectedCategory.label || "请选择类别" }}
        </el-button>
      </el-form-item>

      <!-- 销售人员选择（弹窗） -->
      <el-form-item label="销售人员">
        <el-button type="primary" @click="openDialog('salesman')">
          {{ selectedSalesman.label || "请选择销售人员" }}
        </el-button>
      </el-form-item>

      <!-- 筛选复选框 -->
      <el-form-item>
        <el-checkbox v-model="filter.hideZero">余额为0不显示</el-checkbox>
        <el-checkbox v-model="filter.hideNoTrans">无发生额不显示</el-checkbox>
        <el-checkbox v-model="filter.hideZeroAndNoTrans"
          >余额为0且无发生额不显示</el-checkbox
        >
        <el-checkbox v-model="filter.showDisabled">显示禁用客户</el-checkbox>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="info" @click="resetFilter">重置</el-button>
        <el-button type="primary" @click="queryData">查询</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
        <el-button type="info" @click="printData">打印</el-button>
      </el-form-item>
    </el-form>

    <!-- ========== 客户选择弹窗 ========== -->
    <el-dialog
      title="选择客户"
      v-model="dialogs.customer.visible"
      width="720px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.customer.keyword"
          placeholder="输入客户编号/名称/联系人"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.customer.showDisabled" class="ml-4"
          >显示禁用客户</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchCustomers"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.customer.list"
        :row-key="(row) => row.id"
        @selection-change="handleCustomerSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column
          prop="code"
          label="客户编号"
          min-width="120"
          sortable
        />
        <el-table-column
          prop="name"
          label="客户名称"
          min-width="180"
          sortable
        />
        <el-table-column prop="category" label="客户类别" min-width="120" />
        <el-table-column
          prop="initialReceivable"
          label="期初应收款"
          align="right"
          min-width="140"
          sortable
        />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.customer.limit = val)"
        @current-change="(val) => (dialogs.customer.page = val)"
        :current-page="dialogs.customer.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.customer.limit"
        :total="dialogs.customer.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.customer.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('customer')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 客户类别选择弹窗（树结构） ========== -->
    <el-dialog
      title="选择客户类别"
      v-model="dialogs.customerCategory.visible"
      width="360px"
    >
      <el-tree
        ref="categoryTreeRef"
        :data="customerCategoryTree"
        show-checkbox
        node-key="id"
        :props="{ label: 'label', children: 'children' }"
        @check="handleCategoryCheck"
        default-expand-all
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.customerCategory.visible = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="confirmSelection('customerCategory')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 销售人员选择弹窗 ========== -->
    <el-dialog
      title="选择销售人员"
      v-model="dialogs.salesman.visible"
      width="540px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.salesman.keyword"
          placeholder="输入销售人员编号/名称"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.salesman.showDisabled" class="ml-4"
          >显示禁用人员</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchSalesmen"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.salesman.list"
        :row-key="(row) => row.id"
        @selection-change="handleSalesmanSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="编号" min-width="120" sortable />
        <el-table-column prop="name" label="名称" min-width="180" sortable />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.salesman.limit = val)"
        @current-change="(val) => (dialogs.salesman.page = val)"
        :current-page="dialogs.salesman.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.salesman.limit"
        :total="dialogs.salesman.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.salesman.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection('salesman')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 应收账款表格 ========== -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      show-summary
      :summary-method="generateSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
    >
      <el-table-column
        prop="category"
        label="客户类别"
        min-width="120"
        sortable
      />
      <el-table-column prop="code" label="客户编号" min-width="120" sortable />
      <el-table-column prop="name" label="客户名称" min-width="180" sortable />
      <el-table-column
        prop="initialBalance"
        label="期初余额"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="currentReceivable"
        label="本期应收"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="currentCollection"
        label="本期收款"
        align="right"
        min-width="120"
        sortable
      />
      <el-table-column
        prop="endBalance"
        label="期末余额"
        align="right"
        min-width="120"
        sortable
      />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

// ========== 筛选条件 ==========
const filter = reactive({
  dateRange: [new Date("2025-06-01"), new Date("2025-06-26")],
  summaryBy: "customer", // 汇总依据：customer/customerCategory/salesman
  customer: [], // 选中的客户
  customerCategory: [], // 选中的类别
  salesman: [], // 选中的销售人员
  hideZero: false, // 余额为0不显示
  hideNoTrans: false, // 无发生额不显示
  hideZeroAndNoTrans: false, // 余额为0且无发生额不显示
  showDisabled: false, // 显示禁用客户
});

// ========== 选中项回显 ==========
const selectedCustomer = ref({ label: "" });
const selectedCategory = ref({ label: "" });
const selectedSalesman = ref({ label: "" });

// ========== 对话框状态 ==========
const dialogs = reactive({
  customer: {
    visible: false,
    keyword: "",
    showDisabled: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    selected: [], // 选中的客户行
  },
  customerCategory: {
    visible: false,
    selected: [], // 选中的树节点
    treeRef: ref(null), // 树形组件引用
  },
  salesman: {
    visible: false,
    keyword: "",
    showDisabled: false,
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    selected: [], // 选中的销售人员行
  },
});

// ========== 基础数据模拟 ==========
// 客户类别树（匹配需求层级）
const customerCategoryTree = ref([
  {
    id: 1,
    label: "广东省内",
    children: [],
  },
  {
    id: 2,
    label: "华北地区",
    children: [
      { id: 21, label: "零售" },
      { id: 22, label: "批发" },
    ],
  },
  {
    id: 3,
    label: "华东地区",
    children: [{ id: 31, label: "批发" }],
  },
  {
    id: 4,
    label: "华南地区",
    children: [],
  },
  {
    id: 5,
    label: "华中地区",
    children: [],
  },
]);

// 模拟客户列表（与界面数据一致）
const mockCustomers = [
  {
    id: 1,
    code: "1000000",
    name: "客户1",
    category: "华中地区",
    initialReceivable: 11502.45,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 11502.45,
  },
  {
    id: 2,
    code: "1000001",
    name: "客户2",
    category: "华北地区",
    initialReceivable: 5846.57,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 5846.57,
  },
  {
    id: 3,
    code: "1000002",
    name: "客户3",
    category: "华北地区",
    initialReceivable: 3839.76,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 3839.76,
  },
  {
    id: 4,
    code: "1000003",
    name: "客户4-罗",
    category: "华南地区",
    initialReceivable: 3904.5,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 3904.5,
  },
  {
    id: 5,
    code: "1000004",
    name: "客户5",
    category: "批发",
    initialReceivable: 9907.48,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 9907.48,
  },
  {
    id: 6,
    code: "1000005",
    name: "客户6",
    category: "广东省内",
    initialReceivable: -5018.5,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: -5018.5,
  },
  {
    id: 7,
    code: "1000006",
    name: "客户7",
    category: "华中地区",
    initialReceivable: 7971.24,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 7971.24,
  },
  {
    id: 8,
    code: "1000007",
    name: "客户8",
    category: "批发",
    initialReceivable: 8260.47,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 8260.47,
  },
  {
    id: 9,
    code: "1000008",
    name: "客户9",
    category: "华中地区",
    initialReceivable: 10728.65,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 10728.65,
  },
  {
    id: 10,
    code: "1000009",
    name: "零售",
    category: "零售",
    initialReceivable: 18250.05,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 18250.05,
  },
  {
    id: 11,
    code: "1000010",
    name: "批发",
    category: "批发",
    initialReceivable: 23441.82,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 23441.82,
  },
  {
    id: 12,
    code: "1000013",
    name: "客户",
    category: "",
    initialReceivable: 167.95,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 167.95,
  },
  {
    id: 13,
    code: "1000015",
    name: "小蝶食品",
    category: "广东省内",
    initialReceivable: -7735.67,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: -7735.67,
  },
  {
    id: 14,
    code: "G00009",
    name: "测试111",
    category: "",
    initialReceivable: 0,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 0,
  },
  {
    id: 15,
    code: "G00010",
    name: "深圳蓝天食品公司",
    category: "广东省内",
    initialReceivable: 0,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 0,
  },
  {
    id: 16,
    code: "1000012",
    name: "食品批发中心",
    category: "批发",
    initialReceivable: 0,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 0,
  },
  {
    id: 17,
    code: "1000014",
    name: "要发发食品",
    category: "批发",
    initialReceivable: 0,
    currentReceivable: 0,
    currentCollection: 0,
    endBalance: 0,
  },
];

// 模拟销售人员列表
const mockSalesmen = [
  { id: 1, code: "S001", name: "销售A" },
  { id: 2, code: "S002", name: "销售B" },
  { id: 3, code: "S003", name: "销售C" },
];

// ========== 对话框交互逻辑 ==========
/** 打开对话框 */
const openDialog = (type) => {
  dialogs[type].visible = true;
  if (type === "customer") fetchCustomers();
  if (type === "salesman") fetchSalesmen();
};

/** 获取客户列表（模拟分页+搜索） */
const fetchCustomers = () => {
  const { keyword, showDisabled, page, limit } = dialogs.customer;
  let filtered = mockCustomers.filter(
    (item) => item.code.includes(keyword) || item.name.includes(keyword)
  );
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled); // 模拟禁用逻辑
  }
  // 分页处理
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.customer.list = filtered.slice(start, end);
  dialogs.customer.total = filtered.length;
};

/** 获取销售人员列表（模拟分页+搜索） */
const fetchSalesmen = () => {
  const { keyword, showDisabled, page, limit } = dialogs.salesman;
  let filtered = mockSalesmen.filter(
    (item) => item.code.includes(keyword) || item.name.includes(keyword)
  );
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled); // 模拟禁用逻辑
  }
  // 分页处理
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.salesman.list = filtered.slice(start, end);
  dialogs.salesman.total = filtered.length;
};

/** 客户多选事件 */
const handleCustomerSelect = (val) => {
  dialogs.customer.selected = val;
};

/** 销售人员多选事件 */
const handleSalesmanSelect = (val) => {
  dialogs.salesman.selected = val;
};

/** 类别树复选事件 */
const handleCategoryCheck = (val) => {
  dialogs.customerCategory.selected = val;
};

/** 确认选择（更新筛选条件） */
const confirmSelection = (type) => {
  let label = "";
  if (type === "customer") {
    if (dialogs.customer.selected.length === 0) {
      ElMessage.warning("请选择客户");
      return;
    }
    label = dialogs.customer.selected.map((item) => item.name).join("、");
    filter.customer = dialogs.customer.selected;
  } else if (type === "customerCategory") {
    // 安全获取树形组件选中节点
    const checkedNodes =
      dialogs.customerCategory.treeRef.value?.getCheckedNodes() || [];
    if (checkedNodes.length === 0) {
      ElMessage.warning("请选择类别");
      return;
    }
    label = checkedNodes.map((node) => node.label).join("、");
    filter.customerCategory = checkedNodes;
  } else if (type === "salesman") {
    if (dialogs.salesman.selected.length === 0) {
      ElMessage.warning("请选择销售人员");
      return;
    }
    label = dialogs.salesman.selected.map((item) => item.name).join("、");
    filter.salesman = dialogs.salesman.selected;
  }

  // 更新回显
  if (type === "customer") selectedCustomer.value.label = label;
  if (type === "customerCategory") selectedCategory.value.label = label;
  if (type === "salesman") selectedSalesman.value.label = label;

  // 关闭弹窗
  dialogs[type].visible = false;
  ElMessage.success("选择成功！");
};

/** 重置筛选条件 */
const resetFilter = () => {
  filter.dateRange = [new Date("2025-06-01"), new Date("2025-06-26")];
  filter.summaryBy = "customer";
  filter.customer = [];
  filter.customerCategory = [];
  filter.salesman = [];
  filter.hideZero = false;
  filter.hideNoTrans = false;
  filter.hideZeroAndNoTrans = false;
  filter.showDisabled = false;
  selectedCustomer.value.label = "";
  selectedCategory.value.label = "";
  selectedSalesman.value.label = "";
  ElMessage.success("筛选条件已重置");
};

// ========== 表格数据逻辑 ==========
const tableData = ref([]);

/** 查询数据（模拟筛选） */
const queryData = () => {
  // 1. 筛选客户
  let filteredCustomers = mockCustomers;

  // 按类别过滤
  if (filter.customerCategory.length > 0) {
    filteredCustomers = filteredCustomers.filter((item) =>
      filter.customerCategory.some((cat) => item.category.includes(cat.label))
    );
  }

  // 按选中客户过滤
  if (filter.customer.length > 0) {
    filteredCustomers = filteredCustomers.filter((item) =>
      filter.customer.some((c) => c.id === item.id)
    );
  }

  // 余额/发生额过滤
  if (filter.hideZero) {
    filteredCustomers = filteredCustomers.filter(
      (item) => item.endBalance !== 0
    );
  }
  if (filter.hideNoTrans) {
    filteredCustomers = filteredCustomers.filter(
      (item) => item.currentReceivable !== 0 || item.currentCollection !== 0
    );
  }
  if (filter.hideZeroAndNoTrans) {
    filteredCustomers = filteredCustomers.filter(
      (item) =>
        !(
          item.endBalance === 0 &&
          item.currentReceivable === 0 &&
          item.currentCollection === 0
        )
    );
  }

  // 2. 构建表格数据（可扩展其他汇总维度）
  const result = [];
  filteredCustomers.forEach((customer) => {
    result.push({
      category: customer.category,
      code: customer.code,
      name: customer.name,
      initialBalance: customer.initialReceivable,
      currentReceivable: customer.currentReceivable,
      currentCollection: customer.currentCollection,
      endBalance: customer.endBalance,
    });
  });
  tableData.value = result;
};

/** 合计行计算（期初+期末余额） */
const generateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计:";
      return;
    }
    if (["initialBalance", "endBalance"].includes(column.prop)) {
      const total = data.reduce((acc, item) => acc + item[column.prop], 0);
      sums[index] = total.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

/** 导出（模拟） */
const exportData = () => {
  ElMessage.info("模拟导出...");
};

/** 打印（模拟） */
const printData = () => {
  ElMessage.info("模拟打印...");
};

// ========== 初始化 ==========
onMounted(() => {
  queryData(); // 初始加载数据
});
</script>

<style scoped>
.receivable-summary {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 合计行样式 */
.el-table__footer-row td {
  background-color: #fff2cc !important;
  font-weight: 500;
}

/* 表头样式 */
.el-table th {
  text-align: center;
}
</style>